package org.fixies.utils;

import java.io.ByteArrayOutputStream;

public final class BinaryUtils {


    /**
     * 16進数表記の文字列からバイト配列に変換する
     *
     * @param hex 16進数表記の文字列
     * @return バイト配列
     */
    public static byte[] hexToBytes(String hex) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        hex = format(hex);

        for (int i = 0; i < hex.length(); i += 2) {
            String s = hex.substring(i, i + 2);
            int b = Integer.parseInt(s, 16);
            out.write(b);
        }
        byte[] bytes = out.toByteArray();
        IOUtils.closeQuietly(out);
        return bytes;
    }

    private static String format(String hex) {
        StringBuilder sb = new StringBuilder(hex);
        if (hex.startsWith("0x")) {
            sb.delete(0, 2);
        }
        while (sb.length() > 2 && sb.charAt(0) == '0') {
            sb.deleteCharAt(0);
        }
        if (sb.length() % 2 != 0) {
            sb.insert(0, '0');
        }

        return sb.toString();
    }

    private BinaryUtils() {
    }
}
